package com.ynr.common.utils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ynr.voucher.model.InvoiceModel;

public class InvoiceHandler {

	private static final Logger logger = LoggerFactory.getLogger(InvoiceHandler.class);
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static Map<String, Object> recognize(String filePath) {
		Map<String, Object> invoiceBasicInfoMap = new HashMap<>();
	    Map<String, String> bodyMap = new HashMap<>();
	    //异常处理，若文件不存在
	    bodyMap.put("img", ImageToBase64.convert(filePath));
	    String bodys = JSON.toJSONString(bodyMap);
	    CloseableHttpClient client = HttpClients.createDefault();
	    HttpPost post = new HttpPost(InvoiceConstants.REC_URL);
	    HttpResponse response = null;
	    try {
	    	post.addHeader("Authorization", "APPCODE " + InvoiceConstants.REC_APPCODE);
	    	post.addHeader("Content-Type", "application/json; charset=UTF-8");
	    	post.setEntity(new StringEntity(bodys));
	    	response = client.execute(post);
	    	Map<String, Object> invoiceRecResult = (Map)(((Map)JSON.parse(EntityUtils.toString(response.getEntity()))).get("data"));
	    	if(!invoiceRecResult.isEmpty()) {
	    		invoiceBasicInfoMap.put("fpdm", invoiceRecResult.get("发票代码"));
	    		invoiceBasicInfoMap.put("fphm", invoiceRecResult.get("发票号码"));
	    		invoiceBasicInfoMap.put("kprq", convertChToNum((String)invoiceRecResult.get("开票日期")));
	    		invoiceBasicInfoMap.put("noTaxAmount", invoiceRecResult.get("不含税金额"));
	    		invoiceBasicInfoMap.put("checkCode", invoiceRecResult.get("校验码"));
	    	}
	    } catch (Exception e) {
	    	logger.error("InvoiceHandler recognize method error : {}", e.toString());
	    } finally {
	    	if(client != null) {
	    		try {
					client.close();
				} catch (IOException e) {
					logger.error("InvoiceHandler recognize method close client error : {}", e.toString());
				}
	    	}
	    }
	    return invoiceBasicInfoMap;
	}
	
	public static Map<String, Object> query(Map<String, Object> invoiceBasicInfoMap) {
		Map<String, Object> invoiceDetailInfo = new HashMap<>();
	    List<NameValuePair> list = new ArrayList<NameValuePair>();
        for (String key : invoiceBasicInfoMap.keySet()) {
            list.add(new BasicNameValuePair(key, String.valueOf(invoiceBasicInfoMap.get(key))));
        }
	    CloseableHttpClient client = HttpClients.createDefault();
	    HttpPost post = new HttpPost(InvoiceConstants.QUERY_URL);
	    try {
	    	post.addHeader("Authorization", "APPCODE " + InvoiceConstants.QUERY_APPCODE);
	    	post.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
	    	post.setEntity(new UrlEncodedFormEntity(list, "utf-8"));
	    	HttpResponse response = client.execute(post);
	    	invoiceDetailInfo = (Map)((Map)JSON.parse(EntityUtils.toString(response.getEntity()))).get("data");
	    } catch (Exception e) {
	    	e.printStackTrace();
	    }
	    return invoiceDetailInfo;
	}
	
	private static String convertChToNum(String dataCh) {
		if(!dataCh.isEmpty() && dataCh.length() >= 9) {
			if(Character.isDigit(dataCh.charAt(6))) {
				if(Character.isDigit(dataCh.charAt(9))) {
					return dataCh.substring(0, 4) + dataCh.substring(5, 7) + dataCh.substring(8, 10);
				} else {
					return dataCh.substring(0, 4) + dataCh.substring(5, 7) + "0" + dataCh.substring(8, 9);
				}
			} else {
				if(Character.isDigit(dataCh.charAt(8))) {
					return dataCh.substring(0, 4) + "0" + dataCh.substring(5, 6) + dataCh.substring(7, 9);
				} else {
					return dataCh.substring(0, 4) + "0" + dataCh.substring(5, 6) + "0" + dataCh.substring(7, 8);
				}
			}
		}
		return "";
	}
	
	public static void main(String[] args) {
		//recognize("D:/invoice/2018_09_19_14_21_28.jpg");
		//query(recognize("D:/invoice/2018_09_19_14_24_27.jpg"));
		//System.out.println(convertChToNum("2018年2月2日"));
		Map<String, Object> invoiceBasicInfoMap = new HashMap<>();
		invoiceBasicInfoMap.put("fpdm", "031001800204");
		invoiceBasicInfoMap.put("fphm", "74439704");
		invoiceBasicInfoMap.put("kprq", "20190811");
		invoiceBasicInfoMap.put("noTaxAmount", "97087.38");
		invoiceBasicInfoMap.put("checkCode", "733729");
		Map<String, Object> invoiceMap = query(invoiceBasicInfoMap);
		InvoiceModel invoice = JSON.parseObject(JSON.toJSONString(invoiceMap), InvoiceModel.class);
		System.out.println(JSON.toJSONString(query(invoiceBasicInfoMap)));
	}
	
}
